/**
 * 
 */
package com.ginger.rabbitmq.exchange.api.confirm;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ginger.properties.RabbitMQProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @Description: 生产者
 * @author 姜锋
 * @date 2019年3月29日 上午9:40:05 
 * @version V1.0   
 *
 */
public class Producer {
	/** 日志对象 **/
	private final static Logger logger = LoggerFactory.getLogger(Producer.class);
	public static void main(String[] args) throws Exception {
		// 1.创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		
		//1.1设置连接信息
		connectionFactory.setHost(RabbitMQProperties.RABBITMQ_HOST);
		connectionFactory.setPort(RabbitMQProperties.RABBITMQ_PORT);
		connectionFactory.setVirtualHost(RabbitMQProperties.RABBITMQ_VIRTUAL_HOST);
		connectionFactory.setUsername(RabbitMQProperties.USER_NAME);
		connectionFactory.setPassword(RabbitMQProperties.PASSWORD);
		
		// 2.通过连接工厂创建连接
		Connection connection = connectionFactory.newConnection();
		// 3.通过connection创建
		Channel channel = connection.createChannel();
		
		//4.指定我们的消息投递模式: 消息的确认模式
		channel.confirmSelect();
		
		//5.声明
		String exchangeName = "test_confirm_exchange";
		String routingKey = "confirm.save";
		//6.通过channel发送数据
		
		//for (int i = 0; i < 5; i++) {
			String message =  "这是 1条生产的数据:  Hello RabbitMQ Send confirm message !";
			
			//channel.basicPublish(交换机名称, RouttingKey, properties, 内容);
			channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
				
		//}
		
		// 6.添加确认监听
		
		channel.addConfirmListener(new ConfirmListener() {
			
			/**
			 * 失败返回
			 */
			@Override
			public void handleNack(long deliveryTag, boolean multiple) throws IOException {
				logger.warn("----- no ack! -----");
			}
			/**
			 * 成功返回
			 */
			@Override
			public void handleAck(long deliveryTag, boolean multiple) throws IOException {
				
				logger.warn("----- ack! -----");
			}
		});
		
		//5 关闭连接
		/*
		 * channel.close(); connection.close();
		 */
		
	}
}
